package com.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock condition
 * 两个线程，一个存数据一个取数据——多个线程全部互斥
 */
public class DataLockcondition {
    boolean hasdata;
    int x;
    Lock lock=new ReentrantLock();
    Condition condition=lock.newCondition();
    public void write()
    {
        lock.lock();
        try{
            //有数据
            if (hasdata==true)
            {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //没数据
            System.out.println(Thread.currentThread().getName()+"准备添加数据");
            x=(int)(Math.random()*100000);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"添加数据"+x);
            //通过上述步骤有了数据，并唤醒取数据
            hasdata=true;
            condition.signal();
        }finally {
            lock.unlock();
        }


    }

    public  void get()
    {
        lock.lock();
        try{
            //没有数据
            if (hasdata==false)
            {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"准备读取数据");
            //x=(int)Math.random();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"读取数据为"+x);
            //通过上述步骤没有数据，并唤醒添加数据
            hasdata=false;
            condition.signal();
        }finally {
            lock.unlock();
        }


    }
}
